/**
 * 项目名: school-common
 * 包名:  com.shangde.school.util
 * 文件名: JsonUtils.java
 * Copy Right © 2015 Andronicus Ge
 * 时间: 2015年7月14日
 */
package com.xiaowen.tool;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.text.SimpleDateFormat;

/**
 * @author Andronicus
 * 
 */
@Slf4j
public class JsonUtils {
	private static final int String = 0;
	private static ObjectMapper mapper = new ObjectMapper();

	private JsonUtils() {
	}

	public static String toJson(Object obj) {
		try {
			mapper.setSerializationInclusion(Include.NON_NULL);
			return mapper.writeValueAsString(obj);
		} catch (JsonProcessingException e) {
			log.error(" json to bean 报错 :  {}", e);
			return null;
		}
	}

	public static String toJsonWithDatePattern(Object obj, String pattern) {
		try {
			mapper.setDateFormat(new SimpleDateFormat(pattern));
			return mapper.writeValueAsString(obj);
		} catch (JsonProcessingException e) {
			log.error(e.getMessage(), e);
			return null;
		}
	}

	public static <T> T toBean(String json, Class<T> valueType) {
		if (StringUtils.isEmpty(json)) {
			return null;
		}
		T bean = null;
		try {
			bean = mapper.readValue(json, valueType);
		} catch (Exception e) {
			log.error("字符串 : {} 转换json 出现错误 {}", json, e);
		}
		return bean;
	}

	public static  <T> T toCollectionBean(String json,Class<?> collectionClass, Class<?>... elementClasses){
		T bean = null;
		try{
			JavaType javaType = mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
			bean = mapper.readValue(json,javaType);
		}catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return bean;
	}



}
